package src.array;

import java.util.Arrays;

public class no724 {
    //寻找数组的中心索引，中心左右两边和相等
    public static void main(String[] args) {
        int[] arr = {1, 7, 3, 6, 5, 6};
        System.out.println(pivotIndex2(arr));

    }

    public static int pivotIndex1(int[] nums) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }

        int leftSum = 0;
        int rightSum = 0;
        for (int i = 0; i < nums.length; i++) {
            leftSum += nums[i];
            //rightSum += nums[nums.length - 1 - i];
            rightSum = sum - leftSum + nums[i];  //此时leftSum 里面已经有 nums[i]，多减了一次，所以加上
            //rightSum = sum - leftSum - nums[i+1];
            if (leftSum == rightSum) {
                return i+1;
            }
        }
        return -1;

    }
    public static int pivotIndex2(int[] nums) {
        int leftSum = 0;
        int rightSum = Arrays.stream(nums).sum();  //数组求和
        for (int i = 0; i < nums.length; i++) {

            rightSum -= nums[i];  //右半边先减nums[i]，每次比较时左右的和都不包括nums[i]，leftSum后加
            if (leftSum == rightSum) {
                return i;
            }
            leftSum += nums[i];
        }
        return -1;
    }
}
